package com.liliudong.makabaka.sys.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liliudong.makabaka.sys.entity.SysMenu;
import com.liliudong.makabaka.sys.entity.SysUser;
import com.liliudong.makabaka.sys.mapper.SysMenuMapper;
import com.liliudong.makabaka.sys.mapper.SysUserMapper;
import com.liliudong.makabaka.sys.service.SysUserService;
import com.liliudong.makabaka.sys.vo.SysUserProfileVo;
import com.liliudong.makabaka.util.TreeUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author liudo
 * @description 针对表【sys_user(系统用户)】的数据库操作Service实现
 * @createDate 2023-09-23 16:38:57
 */
@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
        implements SysUserService {

    private final SysMenuMapper sysMenuMapper;

    @Override
    public SysUserProfileVo profile() {
        long userId = StpUtil.getLoginIdAsLong();
        SysUser sysUser = baseMapper.selectById(userId);

        SysUserProfileVo sysUserProfileVo = new SysUserProfileVo();
        BeanUtils.copyProperties(sysUser, sysUserProfileVo);
        // 获取 我的 全部菜单列表
        List<SysMenu> sysMenuList;
        if (StpUtil.hasRole("*")) {
            // 上帝视角
            sysMenuList = sysMenuMapper.selectList(Wrappers.<SysMenu>lambdaQuery()
                    .in(SysMenu::getMenuType, SysMenu.MenuType.M.name(), SysMenu.MenuType.C.name())
            );
        } else {
            sysMenuList = sysMenuMapper.selectListByUserIdNotB(userId);
        }
        // 获取顶级菜单
        Optional<SysMenu> topLevelMenu = sysMenuList.stream().sorted(Comparator.comparing(SysMenu::getParentId))
                .limit(1).findAny();
        if (topLevelMenu.isEmpty()) {
            return null;
        }
        SysMenu topLevelSysMenuOne = topLevelMenu.get();
        List<SysMenu> topLevelMenuList = sysMenuList.stream()
                .filter(sysMenu -> Objects.equals(sysMenu.getParentId(), topLevelSysMenuOne.getParentId()))
                .collect(Collectors.toList());
        List<SysMenu> sysMenus = TreeUtil.getChildrenMenus(topLevelMenuList, sysMenuList);

        sysUserProfileVo.setSysMenuList(sysMenus);
        return sysUserProfileVo;
    }
}




